#!/usr/bin/env python
from os import path, popen
from datetime import datetime
try:
    import pygtk
    pygtk.require("2.0")
except:
    pass

try:
    import gtk, gtk.glade
except Exception, why:
    print why
    import sys; sys.exit(-1)

path_list = ('/usr/share/sms-middleware/gui', 'gui', )
for dir_path in path_list:
    if path.exists(dir_path):
        GUI_DIR = dir_path
        APP_DIR, tail = path.split(dir_path)
        import sys; sys.path.insert(0, APP_DIR)
        break
else:
    raise Exception("No gui data directory found in %s" % path_list)

from plugin_factory import PluginFactory

GLADE_FILE = path.join(GUI_DIR, 'smm.glade')
PID_FILE = '/var/run/sms-middleware.pid'
LOG_TIME_FORMAT = '%y/%m/%d %H:%M:%S'

class SMSMiddlewareGUI:

    def __init__(self):
        self.wTree = gtk.glade.XML(GLADE_FILE)
        self.wTree.signal_autoconnect({
            "install_button_clicked_cb": self.install_button_clicked_cb,
            "start_button_clicked_cb": self.start_button_clicked_cb,
            "stop_button_clicked_cb" : self.stop_button_clicked_cb,
            "restart_button_clicked_cb" : self.restart_button_clicked_cb,
            "notebook_switch_page_cb" : self.notebook_switch_page_cb,
            "SMSMiddlewareGTK_destroy_cb" : gtk.main_quit
        })

        self.init_plugins()
        self.render_plugins()

        self.history_log_buffer = gtk.TextBuffer(table=None)
        history_log = self.wTree.get_widget('history_log').set_buffer(self.history_log_buffer)
        
        self.start_button = self.wTree.get_widget('start_button')
        self.stop_button = self.wTree.get_widget('stop_button')
        if path.isfile(PID_FILE):
            self.history_log_buffer.insert_at_cursor('%s daemon is ON\n' % datetime.today().strftime(LOG_TIME_FORMAT))
        else:
            self.history_log_buffer.insert_at_cursor('%s daemon is OFF\n' % datetime.today().strftime(LOG_TIME_FORMAT))

    def init_plugins(self):
        self.plugin_treeview = self.wTree.get_widget('plugin_treeview')
        self.plugin_model = gtk.ListStore(str, bool)
        self.plugin_treeview.set_model(self.plugin_model)

        renderer = gtk.CellRendererText()
        column0 = gtk.TreeViewColumn("Plugin name", renderer, text=0)
        column0.set_sort_column_id(0)
        self.plugin_treeview.append_column(column0)	

        renderer1 = gtk.CellRendererToggle()
        renderer1.set_property('activatable', True)
        renderer1.connect('toggled', self.plugin_toggled_cb, self.plugin_model)
        column1 = gtk.TreeViewColumn("Running", renderer1)
        column1.add_attribute(renderer1, "active", 1)
        column1.set_sort_column_id(1)
        self.plugin_treeview.append_column(column1)

    def render_plugins(self):
        p_factory.scan_for_plugins()
        self.plugin_model.clear()

        for item in p_factory.active_plugins.values():
            self.plugin_model.append([item['name'], True])

        for item in p_factory.inactive_plugins.values():
            self.plugin_model.append([item['name'], False])

    def plugin_toggled_cb(self, cell, path, model):
        """
        Sets the toggled state on the toggle button to true or false.
        """
        model[path][1] = not model[path][1]
        if model[path][1]: # plugin is active
            for method in p_factory.inactive_plugins.keys():
                if p_factory.inactive_plugins[method]['name'] == model[path][0]:
                    p_factory.activate(method)

        else: # plugin is inactive
            for method in p_factory.active_plugins.keys():
                if p_factory.active_plugins[method]['name'] == model[path][0]:
                    p_factory.deactivate(method)

        return

    def notebook_switch_page_cb(self, widget, a, tab_id):
        if tab_id == 0: #first tab
            self.render_plugins()
        elif tab_id == 1: #second tab
            if path.isfile(PID_FILE): #sms-middleware is running
                self.start_button.set_sensitive(False)
                self.stop_button.set_sensitive(True)
            else: #sms-middleware is OFF
                self.start_button.set_sensitive(True)
                self.stop_button.set_sensitive(False)

    def start_button_clicked_cb(self, widget):
        p = popen('/etc/init.d/sms-middleware start')
        s = ''.join(p.readlines())
        p.close()
        if s.find('(ok)') != -1:
            self.history_log_buffer.insert_at_cursor('%s daemon started\n' % datetime.today().strftime(LOG_TIME_FORMAT))
            self.start_button.set_sensitive(False)
            self.stop_button.set_sensitive(True)
            popen('/usr/bin/notify-send "sms-middleware daemon started"')
        else:
            self.history_log_buffer.insert_at_cursor('%s could not start daemon\n' % datetime.today().strftime(LOG_TIME_FORMAT))

    def stop_button_clicked_cb(self, widget):
        p = popen('/etc/init.d/sms-middleware stop')
        s = ''.join(p.readlines())
        p.close()
        if s.find('(done)') != -1:
            self.history_log_buffer.insert_at_cursor('%s daemon stopped\n' % datetime.today().strftime(LOG_TIME_FORMAT))
            self.start_button.set_sensitive(True)
            self.stop_button.set_sensitive(False)
            popen('/usr/bin/notify-send "sms-middleware daemon stopped"')
        else:
            self.history_log_buffer.insert_at_cursor('%s could not stop daemon\n' % datetime.today().strftime(LOG_TIME_FORMAT))

    def restart_button_clicked_cb(self, widget):
        p = popen('/etc/init.d/sms-middleware restart')
        s = ''.join(p.readlines())
        p.close()
        if s.find('(ok)') != -1:
            self.history_log_buffer.insert_at_cursor('%s daemon restarted\n' % datetime.today().strftime(LOG_TIME_FORMAT))
            self.start_button.set_sensitive(False)
            self.stop_button.set_sensitive(True)
        else:
            self.history_log_buffer.insert_at_cursor('%s could not restart daemon\n' % datetime.today().strftime(LOG_TIME_FORMAT))

    def install_button_clicked_cb(self, widget):
        self.filew = gtk.FileSelection("File selection")
        self.filew.connect("destroy", lambda w: self.filew.hide())
        self.filew.ok_button.connect("clicked", self.file_ok_sel)
        self.filew.cancel_button.connect("clicked", lambda w: self.filew.hide())
        self.filew.show()

    def file_ok_sel(self, widget):
        plugin_filename = self.filew.get_filename()
        p_factory.install(plugin_filename)
        self.render_plugins()

        self.filew.hide()
        self.filew = None        


if __name__ == "__main__":
    from loggers import loggers
    global logger, p_factory
    logger = loggers('smm', None, None, None)

    p_factory = PluginFactory(logger)
    main_pane = SMSMiddlewareGUI()

    gtk.main()

